package javabasic.threads;

public class DeadLock {
    public static void main(String[] args) {
        Object object1 = new Object();
        Object object2 = new Object();
        DeadLockTest deadLock = new DeadLockTest(object1,object2,true);
        DeadLockTest deadLock2 = new DeadLockTest(object1,object2,false);
        Thread thread = new Thread(deadLock);
        Thread thread1 = new Thread(deadLock2);
        thread.start();
        thread1.start();

    }
}

class DeadLockTest implements Runnable{
    private boolean flag;
    private Object obj1;
    private Object obj2;

    public DeadLockTest(Object obj1, Object obj2,boolean flag) {
        this.flag=flag;
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run() {
        if(flag){
            synchronized (this.obj1){
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (this.obj2){
                    System.out.println(Thread.currentThread().getName());
                }
            }

        }else {
            synchronized (this.obj2){
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (this.obj1){
                    System.out.println(Thread.currentThread().getName());
                }
            }

        }
    }

}